<?php

/**
 * @todo Spend comments
 * @todo Write unit test
 *
 */
class WidgetFormOrganizationalUnitCanHaveMembersChoice extends sfWidgetFormDoctrineChoice {
	
	protected function configure($options = array(), $attributes = array()) {
	    $this->addOption('enabled_ids', array());
		parent::configure ( $options, $attributes );
		$this->setOption ( 'model', 'OrganizationalUnit' );
	}
	
	public function getChoices() {
		$choices = array ();
		
		if (false !== $this->getOption ( 'add_empty' )) {
			$choices [''] = true === $this->getOption ( 'add_empty' ) ? '' : $this->translate ( $this->getOption ( 'add_empty' ) );
		}
		
		$treeObject = Doctrine_Core::getTable ( 'OrganizationalUnit' )->getTree ();
		$entities = $treeObject->fetchTree ();
		return $entities;
	}
	
	public function render($name, $value = null, $attributes = array(), $errors = array()) {
		if ($this->getOption ( 'multiple' )) {
			$attributes ['multiple'] = 'multiple';
			
			if ('[]' != substr ( $name, - 2 )) {
				$name .= '[]';
			}
		}
		
		$choices = $this->getChoices ();
		
		return $this->renderContentTag ( 'select', "\n" . implode ( "\n", $this->getOptionsForSelect ( $value, $choices ) ) . "\n", array_merge ( array ('name' => $name ), $attributes ) );
	}
	
	protected function getOptionsForSelect($value, $choices) {
	    $ids = $this->getOption('enabled_ids');
	    $has_ids = count($ids) > 0;
	  
		$mainAttributes = $this->attributes;
		$this->attributes = array ();
		
		if (! is_array ( $value )) {
			$value = array ($value );
		}
		
		$value = array_map ( 'strval', array_values ( $value ) );
		$value_set = array_flip ( $value );
		
		$options = array ();
		foreach ( $choices as $key => $option ) {
		    if(!is_null($option->getDeletedAt())) {
		      continue;
		    }
			$attributes = array ('value' => self::escapeOnce ( $option->getPrimaryKey() ) );
			if (isset ( $value_set [strval ( $option->getPrimaryKey() )] )) {
				$attributes ['selected'] = 'selected';
			}
			if(!$option->canHaveMembers() || ($has_ids && !in_array($option->getId(), $ids))) {
				$attributes['disabled'] = 'disabled';
			}
			
			$options [] = $this->renderContentTag ( 'option', str_repeat('&nbsp;&nbsp;&nbsp;', $option->getLevel()) . self::escapeOnce ( $option ), $attributes );
		}
		
		$this->attributes = $mainAttributes;
		
		return $options;
	}
}